import 'package:flutter/material.dart';
import 'dart:async';

import 'package:flutter/services.dart';
import 'package:mpaas/mpaas.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  String _platformVersion = 'Unknown';
  String _token = 'No token received yet';
  final _mpaasPlugin = Mpaas();
  final GlobalKey<ScaffoldMessengerState> _scaffoldMessengerKey = GlobalKey<ScaffoldMessengerState>();

  @override
  void initState() {
    super.initState();
    initPlatformState();
  }

  @override
  void dispose() {
    super.dispose();
  }

  // Platform messages are asynchronous, so we initialize in an async method.
  Future<void> initPlatformState() async {
    // 首先开始监听推送 token 事件
    print('开始监听 token 事件...');

    String platformVersion;
    // Platform messages may fail, so we use a try/catch PlatformException.
    // We also handle the message potentially returning null.
    try {
      platformVersion =
          await _mpaasPlugin.getPlatformVersion() ?? 'Unknown platform version';
    } on PlatformException {
      platformVersion = 'Failed to get platform version.';
    }

    String token;
    try {
      token = await _mpaasPlugin.pushGetToken() ?? 'Unknown token';
    } on PlatformException {
      token = 'Failed to get platform version.';
    }

    // If the widget was removed from the tree while the asynchronous platform
    // message was in flight, we want to discard the reply rather than calling
    // setState to update our non-existent appearance.
    if (!mounted) return;

    setState(() {
      _platformVersion = platformVersion;
      _token = token;
    });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      scaffoldMessengerKey: _scaffoldMessengerKey,
      home: Scaffold(
        appBar: AppBar(title: const Text('Plugin example app')),
        body: Column(
          children: [
            Center(child: Text('Running on: $_platformVersion\n')),
            Center(child: Text('Token: $_token\n')),
            ElevatedButton(
              onPressed: () async {
                try {
                  final res = await _mpaasPlugin.pushBindUserId("123456");
                  if (res) {
                    // 成功提示
                    _scaffoldMessengerKey.currentState?.showSnackBar(
                      SnackBar(
                        content: Text('User ID bound successfully'),
                        backgroundColor: Colors.green,
                      ),
                    );
                  } else {
                    // 失败提示
                    _scaffoldMessengerKey.currentState?.showSnackBar(
                      SnackBar(
                        content: Text('Failed to bind User ID'),
                        backgroundColor: Colors.orange,
                      ),
                    );
                  }
                } on PlatformException catch (e) {
                  // 处理 PlatformException 错误
                  print('PlatformException: ${e.code} - ${e.message}');
                  
                  // 使用全局 ScaffoldMessenger
                  _scaffoldMessengerKey.currentState?.showSnackBar(
                    SnackBar(
                      content: Text('Platform Error: ${e.message ?? e.code}'),
                      backgroundColor: Colors.red,
                      duration: Duration(seconds: 3),
                    ),
                  );
                } catch (e) {
                  // 处理其他类型的错误
                  print('Other error: $e');
                  
                  // 使用全局 ScaffoldMessenger
                  _scaffoldMessengerKey.currentState?.showSnackBar(
                    SnackBar(
                      content: Text('Unexpected Error: $e'),
                      backgroundColor: Colors.red,
                      duration: Duration(seconds: 3),
                    ),
                  );
                }
              },
              child: const Text('绑定userId'),
            ),
            SizedBox(height: 10),
            ElevatedButton(
              onPressed: () async {
                try {
                  final res = await _mpaasPlugin.pushUnbindUserId("123456");
                  if (res) {
                    // 成功提示
                    _scaffoldMessengerKey.currentState?.showSnackBar(
                      SnackBar(
                        content: Text('User ID unbound successfully'),
                        backgroundColor: Colors.green,
                      ),
                    );
                  } else {
                    // 失败提示
                    _scaffoldMessengerKey.currentState?.showSnackBar(
                      SnackBar(
                        content: Text('Failed to unbind User ID'),
                        backgroundColor: Colors.orange,
                      ),
                    );
                  }
                } on PlatformException catch (e) {
                  // 处理 PlatformException 错误
                  print('Unbind PlatformException: ${e.code} - ${e.message}');
                  
                  // 使用全局 ScaffoldMessenger
                  _scaffoldMessengerKey.currentState?.showSnackBar(
                    SnackBar(
                      content: Text('Platform Error: ${e.message ?? e.code}'),
                      backgroundColor: Colors.red,
                      duration: Duration(seconds: 3),
                    ),
                  );
                } catch (e) {
                  // 处理其他类型的错误
                  print('Unbind Other error: $e');
                  
                  // 使用全局 ScaffoldMessenger
                  _scaffoldMessengerKey.currentState?.showSnackBar(
                    SnackBar(
                      content: Text('Unexpected Error: $e'),
                      backgroundColor: Colors.red,
                      duration: Duration(seconds: 3),
                    ),
                  );
                }
              },
              child: const Text('解绑userId'),
            ),
            SizedBox(height: 10),
            ElevatedButton(
              onPressed: () async {
                try {
                  final res = await _mpaasPlugin.pushBindUserIdWithPhone("123456", "13812345678");
                  if (res) {
                    // 成功提示
                    _scaffoldMessengerKey.currentState?.showSnackBar(
                      SnackBar(
                        content: Text('User ID and phone bound successfully'),
                        backgroundColor: Colors.green,
                      ),
                    );
                  } else {
                    // 失败提示
                    _scaffoldMessengerKey.currentState?.showSnackBar(
                      SnackBar(
                        content: Text('Failed to bind User ID with phone'),
                        backgroundColor: Colors.orange,
                      ),
                    );
                  }
                } on PlatformException catch (e) {
                  // 处理 PlatformException 错误
                  print('Bind phone PlatformException: ${e.code} - ${e.message}');
                  
                  // 使用全局 ScaffoldMessenger
                  _scaffoldMessengerKey.currentState?.showSnackBar(
                    SnackBar(
                      content: Text('Platform Error: ${e.message ?? e.code}'),
                      backgroundColor: Colors.red,
                      duration: Duration(seconds: 3),
                    ),
                  );
                } catch (e) {
                  // 处理其他类型的错误
                  print('Bind phone Other error: $e');
                  
                  // 使用全局 ScaffoldMessenger
                  _scaffoldMessengerKey.currentState?.showSnackBar(
                    SnackBar(
                      content: Text('Unexpected Error: $e'),
                      backgroundColor: Colors.red,
                      duration: Duration(seconds: 3),
                    ),
                  );
                }
              },
              child: const Text('绑定userId+手机号'),
            ),
          ],
        ),
      ),
    );
  }
}
